package com.myflink.day03;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Shelly An
 * @create 2020/9/18 10:46
 */
public class Operator_Process {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        DataStreamSource<String> fileDS = env.readTextFile("input/sensor-data.log");
        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> sensorDS = fileDS.map(new MapFunction<String, Tuple3<String, Long, Integer>>() {

            @Override
            public Tuple3<String, Long, Integer> map(String value) throws Exception {
                String[] datas = value.split(",");
                //开发中，用包装类多一些。 parse返回的是基本类型
                return new Tuple3<>(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        });

        KeyedStream<Tuple3<String, Long, Integer>, String> sensorKS = sensorDS.keyBy(r -> r.f0);


        //所有的流都可以调用，返回值类型不同。 co 或 单一
        // 可以获取到一些环境信息 process是一个比较底层的方法
        SingleOutputStreamOperator<String> result = sensorKS.process(new KeyedProcessFunction<String, Tuple3<String, Long, Integer>, String>() {
            /**
             * 处理数据的方法，来一条处理一条
             * @param value 一条数据
             * @param ctx 上下文
             * @param out 采集器
             * @throws Exception
             */
            @Override
            public void processElement(Tuple3<String, Long, Integer> value, Context ctx, Collector<String> out) throws Exception {
                out.collect("当前key=" + ctx.getCurrentKey() + ", 数据：" + value);
            }
        });

        result.print("process");

        env.execute();
    }
}
